package com.hboxs.asl.wechat.service.impl;

import com.hboxs.asl.Filter;
import com.hboxs.asl.service.impl.BaseServiceImpl;
import com.hboxs.asl.wechat.dao.WxOrderDao;
import com.hboxs.asl.wechat.entity.WxOrder;
import com.hboxs.asl.wechat.service.WxOrderService;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by hboxs on 18/8/15.
 */
@Service("wxOrderServiceImpl")
public class WxOrderServiceImpl extends BaseServiceImpl<WxOrder, Long> implements WxOrderService {

    @Resource(name = "wxOrderDaoImpl")
    private WxOrderDao wxorderDao;

    @Resource(name = "wxOrderDaoImpl")
    public void setBaseDao(WxOrderDao wxOrderDao) {
        super.setBaseDao(wxOrderDao);
    }

    @Override
    public WxOrder findByOutTradeNo(String outTradeNo) {
        Assert.notNull(outTradeNo);

        List<Filter> filters = new ArrayList<>();
        filters.add(Filter.eq("outTradeNo", outTradeNo));

        List<WxOrder> wxOrders = findList(1, filters, null);

        if (wxOrders.size() > 0) return wxOrders.get(0);

        return null;
    }

    @Override
    public WxOrder findByTransactionId(String transactionId) {
        Assert.notNull(transactionId);

        List<Filter> filters = new ArrayList<>();
        filters.add(Filter.eq("transactionId", transactionId));

        List<WxOrder> wxOrders = findList(1, filters, null);

        if (wxOrders.size() > 0) return wxOrders.get(0);

        return null;
    }

    @Override
    public boolean deleteFailOrder() {
        List<Filter> filters = new ArrayList<>();
        filters.add(Filter.isNull("paymentResult"));
        try {
            List<WxOrder> wxOrders = findList(null, filters, null);
            Long[] ids = new Long[wxOrders.size()];
            int index = 0;
            for (WxOrder wxOrder : wxOrders) {
                ids[index++] = wxOrder.getId();
            }
            delete(ids);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }


        return false;
    }

    @Override
    public List<WxOrder> listWxOrder(String orderType) {
        return wxorderDao.listWxOrder(orderType);
    }
}
